package org.dragonnova.business.dao;

import java.util.List;
import java.util.Map;

import org.dragonnova.business.model.Pager;
import org.dragonnova.business.model.User;
import org.dragonnova.business.util.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

@Repository
public class UsersDao extends BaseDao {

	public List<User> getAllUser() throws Exception {
		String hsql = "from t_tmp_users";
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery(hsql);
		return query.list();
	}

	/**
	 * 查询用户
	 * 
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> findUser(Map<String, Object> map) throws Exception {
		StringBuffer hsql = new StringBuffer("from t_tmp_users where 1=1");
		String id = (String) map.get("id");
		String searchText = (String) map.get("searchText");
		Pager page = (Pager) map.get("page");
		if (id != null) {
			hsql.append(" and id=");
			hsql.append(id);
		}
		if (searchText != null) {
			searchText = StringUtils.concat("'%", searchText, "%'");
			hsql.append(" and (user_name like " + searchText + " mobile like " + searchText);
		}
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery(hsql.toString());
		page.setTotalPage(query.list().size());
		query.setMaxResults(page.getPageSize());
		query.setFirstResult(page.getFirstIndex());
		List<User> list = query.list();
		if (list != null) {
			for (User u : list) {
				u.setPassword("");
			}
		}
		return packData(list, page);
	}

	/**
	 * 修改密码
	 * 
	 * @param id
	 * @param md5DigestAsHex
	 * @throws Exception
	 */
	public int updatePassword(Integer id, String newPwd) throws Exception {
		Session session = sessionFactory.openSession();
		Transaction trans = session.beginTransaction();
		Query query = session.createQuery("update t_tmp_users t set t.password = ? where id = ?");
		query.setParameter(0, newPwd);
		query.setParameter(1, id);
		int result = query.executeUpdate();
		trans.commit();
		session.close();
		return result;
	}

}
